#include "annotationimage.h"

using namespace cv;
cv::Scalar COLOR(255, 0, 255);
cv::Scalar TMP_COLOR(0, 255, 0);

bool AnnotationImage::read()
{
    imageData = cv::imread(imageFileName);

    if (!imageData.data)
        return false;
    ratateAngle = 0.0;

    pImageAnn = new ImageAnnotation(imageFileName, getAnnNameByImageName(imageFileName), this);

    return true;
}

cv::Mat AnnotationImage::drawAnnInImage(int index)
{
    cv::Mat tmp;
    imageData.copyTo(tmp);

    drawDataInImage(tmp, pImageAnn->getImageEntries(), index);

    return tmp;
}

cv::Mat AnnotationImage::drawAnnInImage(ImageAnnItem &polyData, int index)
{
    cv::Mat tmp;
    imageData.copyTo(tmp);

    // 如果polyData不为空，则先在图片上将多边形画出来
    if (polyData.getPoints().size() != 0)
    {
        if(polyData.getAnnType() == Polygon_Type)
            cv::polylines(tmp, polyData.getPoints(), true, TMP_COLOR, THICKNESS);
        else if(polyData.getAnnType() == Rectangle_Type)
        {
            vector<cv::Point> pts = polyData.getPoints();
            if(pts.size() != 2)
                cout << "Ops! Rectangle size != 2" << endl;
            Point p0 = pts[0], p1 = pts[1];
            if(p0 != p1)
            {
                if(p0.x < p1.x)
                    rectangle(tmp, p0, p1, TMP_COLOR, THICKNESS);
                else if(p0.x > p1.x)
                    rectangle(tmp, p1, p0, TMP_COLOR, THICKNESS);
            }
        }
    }

    drawDataInImage(tmp, pImageAnn->getImageEntries(), index);

    return tmp;
}

void AnnotationImage::drawDataInImage(cv::Mat & tmp, vector<ImageAnnEntry>& entries, int index)
{
//    for(auto item : entries[index].getImageItems())
//    {
//        if (item.getAnnType() == Point_Type)
//            for (auto p : item.getPoints())
//                cv::circle(tmp, p, RADIUS, entries[index].getColor(), -1);
//        else if (item.getAnnType() == Rectangle_Type || item.getAnnType() == Polygon_Type)
//            cv::polylines(tmp, item.getPoints(), true, entries[index].getColor(), THICKNESS);
//    }

    // 将标注在图片上画出来
    int i = 0;
    for(auto entry : entries)
    {
        if(i != index)
        {
            i++;
            continue;
        }
       for(auto item : entry.getImageItems())
       {
           if (item.getAnnType() == Point_Type)
               for (auto p : item.getPoints())
                   cv::circle(tmp, p, RADIUS, entry.getColor(), -1);
           else if (item.getAnnType() == Rectangle_Type || item.getAnnType() == Polygon_Type)
               cv::polylines(tmp, item.getPoints(), true, entry.getColor(), THICKNESS);
       }
       i++;
    }
}
